<template>
  <div class="rule-box">
    <div v-if="$route.query.name" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <el-form ref="formRef" :model="form">
      <step1
        ref="step1Ref"
        :step1-data="form1"
      />
      <step2
        ref="step2Ref"
        :echo-table-data="echoTableData"
        :is-check.sync="isShow"
        :step2-data="form2"
        @handleCheck="next"
      />
      <step3
        ref="step3Ref"
        :table-data="tableData"
        :is-check="isShow"
        :step3-data="form3"
        :import-product="form.importProduct"
        :dialog-data="step2Data.dialogEchoData"
        :context-list="contextList"
      />
    </el-form>
    <div class="footer" style="text-align: right">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="$router.go(-1)">取 消</el-button>
    </div>
  </div>
</template>

<script>
import step1 from './coms/step1'
import step2 from './coms/step2'
import step3 from './coms/step3'
import { validationName, saveRulePolicy, getRulePolicy } from '@/api/milkyway/accessRules'
import { mapState, mapMutations } from 'vuex'

export default {
  components: { step1, step2, step3 },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true
    next()
  },
  data() {
    return {
      active: 0,
      ruleForm: {},
      tableData: [],
      echoTableData: [],
      step1Data: {},
      step2Data: {},
      //  逻辑判断第一个下拉框数据
      contextList: [],
      submitParam: {},
      formData: {},
      isEdit: false,
      isShow: false,
      form: {
        name: '',
        type: 'grok',
        context: null,
        productId: '',
        ruleContext: null,
        importProduct: [],
        isShow: false,
        isValidate: false,
        formData: {
          id: []
        },
        relationDatas: {
          flag: 'and',
          subSyntaxExpressnList: []
        }
      }
    }
  },
  computed: {
    form1: {
      get() {
        return this.form
      }
    },
    form2: {
      get() {
        return this.form
      }
    },
    form3: {
      get() {
        return this.form.formData
      }
    }
  },
  mounted() {
    this.step1Data = {}
    this.step2Data = {}
    if (this.$route.params.id == 'add') {
      this.isEdit = false
      this.formData = {}
    } else {
      this.isEdit = true
      this.isShow = true
      getRulePolicy(this.$route.params.id).then((res) => {
        this.form = { ...res.step1Data, formData: res.step2Data.formData }
        if (this.form.formData.id.length > 0) {
          this.$refs.step3Ref.cascaderHandleChange(this.form.formData.id)
        }
        this.$nextTick(() => {
          this.step1Data = res.step1Data
          this.step2Data = res.step2Data
          this.tableData = res.step2Data.rightTableData
          this.echoTableData = res.step2Data.rightTableData
        })
      })
    }
  },
  methods: {
    ...mapMutations({
      CHANGECLEAN: 'ruleParsing/CHANGECLEAN',
      CLEANDIALOGECHODATA: 'ruleParsing/CLEANDIALOGECHODATA'
    }),
    back() {
      this.active--
    },
    async next(res) {
      await this.handleValidate({ tableData: res.tableData, contextList: res.contextList })
      this.step1Data = Object.assign({}, res, this.form)
    },
    cancel() {
      this.CHANGECLEAN()
      this.CLEANDIALOGECHODATA()
      this.$router.back()
    },
    /** 保存 */
    async submitForm() {
      await this.$refs.step1Ref.handleSubmit()
      await this.$refs.step2Ref.handleSubmit()
      const currentId = this.$route.params.id ? this.$route.params.id : 'add'
      if (!this.isShow) {
        this.$message.error('请对数据进行解析')
        return
      }
      this.step1Data = Object.assign(this.step1Data, this.form)
      this.step1Data.relationDatas = this.$refs.step2Ref.relationData
      await validationName({
        id: currentId == 'add' ? '' : currentId,
        name: this.step1Data.name
      })
      this.$refs.step3Ref.handleSubmit().then((res) => {
        this.step2Data = res.secondEchoData
        this.submitParam.rulePolicy = {
          mdId: res.mdId[1],
          name: this.step1Data.name,
          productId: this.step1Data.importProduct[this.step1Data.importProduct.length - 1],
          ruleExpression: this.step1Data.relationDatas
        }
        this.submitParam.messageAnalysis = {
          messageContext: this.step1Data.context,
          messageType: this.step1Data.type,
          messageRule: this.step1Data?.ruleContext || ''
        }
        this.submitParam.dataColumnRuleList = res.dataColumnRuleList
        if (this.isEdit) {
          saveRulePolicy({
            id: this.$route.params.id,
            submitParam: this.submitParam,
            echoData: { step1Data: this.step1Data, step2Data: this.step2Data }
          }).then((res) => {
            this.CHANGECLEAN()
            this.CLEANDIALOGECHODATA()
            this.$message.success('保存成功')
            this.$router.push({ path: window.prefix + '/mlk/access/rule' })
          })
        } else {
          saveRulePolicy({
            submitParam: this.submitParam,
            echoData: { step1Data: this.step1Data, step2Data: this.step2Data }
          }).then((res) => {
            this.CHANGECLEAN()
            this.CLEANDIALOGECHODATA()
            this.$message.success('保存成功')
            this.$router.push({ path: window.prefix + '/mlk/access/rule' })
          })
        }
      })
    },

    /** 第一步校验完成，获取列表数据 */
    handleValidate(data) {
      this.tableData = data.tableData.map((i) => {
        return {
          columnName: i.columnName,
          columnValue: i.columnValue,
          columnType: i.columnType,
          metaName: undefined,
          columnDesc: undefined
        }
      })
      let isEditTable = []
      let noEditTable = []
      if (this.step2Data?.rightTableData) {
        noEditTable = this.step2Data.rightTableData.filter((item, index) => {
          return item.columnType == 0
        })
        if (noEditTable.length > 0) {
          this.tableData.forEach((i, index) => {
            noEditTable.forEach((item, indx) => {
              if (i.columnName == item.columnName) {
                this.tableData[index].metaName = item?.metaName
                this.tableData[index].columnDesc = item?.columnDesc
              }
            })
          })
        }
        isEditTable = this.step2Data.rightTableData.filter((item, index) => {
          return item.columnType == 1
        })
      }
      this.tableData = this.tableData.concat(isEditTable)
      this.contextList = data.contextList
    }
  }
}
</script>

<style lang="scss" scoped>
#app.dark-theme .rule-box{
  background: transparent;
  .in-block{
    color: #fff;
    background: rgba(59,139,255,0.10);
  }
}
.rule-box {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #eef0f5;
  .el-form{
    flex:1;
    overflow:auto;
  }

  .in-block{
    background: #fff;
    padding: 20px;
    &::v-deep{
      .title{
        font-weight: 700;
        font-size: 20px;
        margin-bottom: 10px;
      }
    }
    &+.in-block{
      margin-top: 20px;
    }
  }
}
.footer{
  width: 100%;
  bottom: 0;
  right: 0px;
  padding: 10px 20px;
  text-align: right;
  background: #fff;
  margin-top: 20px;
}
</style>
